package com.liglei.wol;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * Wake On Lan 技术，远程打开电脑
 * @Author:
 * @CreateTime: 2024-05-31  10:27
 * @Description:
 * @Version: 1.0
 */
public class Low {
    public static void main(String[] args) {
        // 18:C0:4D:6D:4D:A3 192.168.1.194 1.192.63.19
        // D8:BB:C1:4E:F5:4C 192.168.1.6
        String wake = Low.Wake("", "192.168.1.255", "D8:BB:C1:4E:F5:4C", 8888);
        System.out.println(wake);
    }

    /**
     *  发送数据到指定地址
     * @ClassName Low
     * @Date 2024/6/4  10:50
     * @Version 1.0
     * @param name 随便的标记名字
     * @param host 要操控PC的 IP / 域名 / 广播地址如： 192.168.1.194/ baidu.com / 192.168.1.255
     * @param mac PC的MAC地址 18:C0:4D:6D:4D:A3
     * @param port 发送到PC的端口 默认一般是7 或者 9
     */
    private static String Wake(String name, String host, String mac, int port) {
        try {
            byte[] macBytes = getMacBytes(mac);//转成字节类型
            byte[] bytes = new byte[6 + 16 * macBytes.length];
            for (int i = 0; i < 6; i++) {
                bytes[i] = (byte) 0xff;
            }
            for (int i = 6; i < bytes.length; i += macBytes.length) {
                System.arraycopy(macBytes, 0, bytes, i, macBytes.length); //放入16个MAC地址
            }
            InetAddress address = InetAddress.getByName(host);
            System.out.println("address = " + address);
            DatagramPacket packet = new DatagramPacket(bytes, bytes.length, address, port);
            DatagramSocket socket = new DatagramSocket();
            socket.send(packet);
            socket.close();
            return "wol_package_sent_successfully";
        } catch (Exception e) {
            return "wol_packet_sending_failed";
        }
    }

    private static byte[] getMacBytes(String mac) throws IllegalArgumentException {
        byte[] bytes = new byte[6];
        String[] hex = mac.split("(\\:|\\-)");
        if (hex.length != 6) {
            throw new IllegalArgumentException("Invalid MAC address.");
        }
        try {
            for (int i = 0; i < 6; i++) {
                bytes[i] = (byte) Integer.parseInt(hex[i], 16);
            }
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("Invalid hex digit in MAC address.");
        }
        return bytes;
    }
}
